package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.bo.SpuBo;
import com.leyou.item.mapper.*;
import com.leyou.item.pojo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsService {
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;
    /**
     * 根据条件分页查询spu
     * @param key
     * @param saleable
     * @param page
     * @param rows
     * @return
     */
    public PageResult<SpuBo> querySpuBoByPage(String key, Boolean saleable, Integer page, Integer rows) {
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        //添加查询条件
        if(StringUtils.isNotBlank(key)){
            //不为空则添加模糊查询
            criteria.andLike("title","%"+key+"%");
        }
        //添加上下架的过滤条件
        if(saleable!=null){
            criteria.andEqualTo("saleable",saleable);
        }
        //添加分页
        PageHelper.startPage(page,rows);
        //执行查询，获取spu集合
        List<Spu> spus = spuMapper.selectByExample(example);
        //获取pageInfo对象
        PageInfo<Spu> pageInfo = new PageInfo<>(spus);
        //spu集合转化为spubo集合
        List<SpuBo> spuBos = spus.stream().map(spu -> {
            SpuBo spuBo = new SpuBo();
            BeanUtils.copyProperties(spu, spuBo);

            //查询品牌名称
            Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
            spuBo.setBname(brand.getName());
            //查询分类名称
            List<String> names = categoryService.queryNamesByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            spuBo.setCname(StringUtils.join(names, "-"));
            return spuBo;
        }).collect(Collectors.toList());
        //返回PageResult<SpuBo>
        return new PageResult<>(pageInfo.getTotal(),spuBos);
    }
    /**
     * 新增商品
     * @param spuBo
     * @return
     */
    @Transactional
    public void saveGoods(SpuBo spuBo) {
        //先新增spu
        spuBo.setId(null);
        spuBo.setSaleable(true);
        spuBo.setValid(true);
        spuBo.setCreateTime(new Date());
        spuBo.setLastUpdateTime(new Date());
        spuMapper.insertSelective(spuBo);
        //在新增spuDetail
        SpuDetail spuDetail = spuBo.getSpuDetail();
        //主键回显得到保存后的spu id
        spuDetail.setSpuId(spuBo.getId());
        spuDetailMapper.insertSelective(spuDetail);
        //skus是一个集合，包含了sku和stock的字段
        saveSkuAndStock(spuBo);
        sendMsg("insert", spuBo.getId());
    }
    /**
     * 更新商品信息
     * @param spuBo
     * @return
     */
    @Transactional
    public void updateGoods(SpuBo spuBo) {
        //删除旧的stock
        Sku sku = new Sku();
        //根据spuId查询sku集合
        sku.setSpuId(spuBo.getId());
        List<Sku> skus = skuMapper.select(sku);
        for(Sku sku1:skus){
            //通过skuId删除对应的stock
            stockMapper.deleteByPrimaryKey(sku1.getId());
        }
        //删除旧的sku
        skuMapper.delete(sku);
        //新增sku新增stock
        saveSkuAndStock(spuBo);
        //更新spu和spuDetail
        //设置为null的字段不允许更新
        spuBo.setCreateTime(null);
        spuBo.setValid(null);
        spuBo.setSaleable(null);
        spuBo.setLastUpdateTime(new Date());
        spuMapper.updateByPrimaryKeySelective(spuBo);
        spuDetailMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());
        sendMsg("update",spuBo.getId());
    }
    /**
     * 根据spuId查询spuDeatil
     * @param spuId
     * @return
     */
    public SpuDetail querySpuDetailBySpuId(Long spuId) {
        return spuDetailMapper.selectByPrimaryKey(spuId);
    }
    /**
     * 根据spuId查询sku集合
     * @param spuId
     * @return
     */
    public List<Sku> querySkusBySpuId(Long spuId) {
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skus = skuMapper.select(sku);
        //通过skus的id获取对应的库存信息
        for(Sku sku1:skus){
            Stock stock = stockMapper.selectByPrimaryKey(sku1.getId());
            //将库存设置到每个sku中
            sku1.setStock(stock.getStock());
        }
        //返回结果
        return skus;
    }

    /**
     * 新增sku和stock
     * @param spuBo
     */
    public void saveSkuAndStock(SpuBo spuBo){
        for(Sku sku:spuBo.getSkus()){
            //新增sku
            sku.setId(null);
            sku.setSpuId(spuBo.getId());
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(new Date());
            skuMapper.insertSelective(sku);
            //新增stock
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            stockMapper.insertSelective(stock);
        }
    }
    /**
     * 根据id查询spu
     * @param spuId
     * @return
     */
    public Spu querySpuById(Long spuId) {
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        return spu;
    }

    /**
     * Rabbitmq发送消息
     * @param type
     * @param id
     */
    public void sendMsg(String type,Long id){
        try{
            amqpTemplate.convertAndSend("item."+type,id);
        }catch (Exception e){

        }
    }

    /**
     * 通过id查询sku
     * @param skuId
     * @return
     */
    public Sku querySkuBySkuId(Long skuId) {
       return skuMapper.selectByPrimaryKey(skuId);

    }
}
